<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 返回json格式错误信息
 * @param $msg
 */
function json_error_msg($msg){
    $arr['success'] = false;
    $arr['msg'] =  $msg;
    echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    die;
}

/**
 * @param $oj 返回错误信息
 */
function  json_success_msg($obj){
    if(false === $obj){
        json_error_msg($obj);
    }
    $result['success'] = true;
    $result['obj'] = $obj;
    echo json_encode($result);
    die;
}

/**
 * 返回json格式错误信息
 * @param $msg
 */
function json_return_code($obj='',$msg='成功', $code=200){
    $arr['success'] = $code==200?true:false;
    $arr['code'] = $code;
    $arr['msg'] =  $msg;
    $arr['obj'] = $obj;
    echo json_encode($arr,JSON_UNESCAPED_UNICODE);
    die;
}

function is_true($val, $return_null=false){
    $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
    return ( $boolval===null && !$return_null ? false : $boolval );
}

/**
 * 对sqlserver 数据库  float 进行处理
 * @param $arr
 * @return string
 */
function getNumField($arr){
    $resultStr = '' ;
    foreach ($arr as $colkey){
        $resultStr.= "convert(varchar(20),cast(round($colkey,3) as numeric(15,3))) as $colkey" .',';
    }
    return $resultStr;
}

/**
 * 添加日志
 * @param $common
 */
function addLog($common){
    $user_id = input('opt_user_id');
    $user_name = input('opt_user_name');
    $model = new \app\common\model\SysLog();
    $data = [
        'user_id'=>$user_id,
        'user_name'=>$user_name,
        'opt_name'=>$common,
        'common'=>json_encode(input(),128|256),
        'add_datetime'=>date('Y-m-d H:i:s')
    ];
    $model->insert($data);
}

/**
 * 根据经纬度计算距离sql
 * @param $lat
 * @param $lng
 * @return string
 */
function distance_sql($lat, $lng){
    $sql = "round(((6371.004* ACOS(
            COS(RADIANS($lat))* COS(RADIANS(`lat`))* COS(RADIANS($lng) - RADIANS(`lng`))
            + SIN(RADIANS($lat))* SIN(RADIANS(`lat`))
        ))*1000),2)";

     return $sql;
}

function json_tab_msg($count, $page, $obj,$msg=''){
    $arr['code'] = 0;
    $arr['msg'] =  $msg;
    $arr['count'] =  $count;
    $arr['page'] =  $page;
    $arr['data'] =  $obj;
    return json($arr);
}

function json_msg($msg, $flag=false, $obj=''){
    if(false === $obj){
        json_msg($obj);
    }
    $arr['success'] = $flag;
    $arr['msg'] =  $msg;
    $arr['data'] =  $obj;
    return json($arr);
}

function export_excle($info, $table_title, $table_value, $table_name='Excel') {
    //防止内存溢出
    ini_set('memory_limit','1024M');
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
// 设置文档属性
    $spreadsheet->getProperties()->setCreator("")
        ->setLastModifiedBy("")
        ->setTitle("数据EXCEL导出")
        ->setSubject("数据EXCEL导出")
        ->setDescription("数据EXCEL导出")
        ->setKeywords("excel")
        ->setCategory("result file");
// 定义列名数组
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

// 写入表头
    foreach ($table_title as $index => $title) {
        $column = $cellName[$index];
        $sheet->setCellValue($column . '1', $title);
    }
// 写入数据行
    $rowIndex = 2; // 开始从第二行写入数据（第一行为标题）
    foreach ($info as $rowData) {
        foreach ($table_value as $index => $field) { // 假设 $table_value 包含字段名
            $column = $cellName[$index];
            $sheet->setCellValue($column . $rowIndex, $rowData[$field]);
        }
        $rowIndex++;
    }

    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    $files = '财务对账'.date('YmdHis').'.xlsx';
    //获取文件内容
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition:attachment;filename=' . $files);//声明作为附件处理和下载后文件的名称
    header('Cache-Control: max-age=0');
    $writer->save('php://output');
    exit;
}

function export_excle1($info, $table_title, $table_value, $table_name='Excel') {
    //防止内存溢出
    ini_set('memory_limit','1024M');
    vendor('PHPExcel.PHPExcel');
    header("content-type:text/html;charset=utf8");
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties()->setCreator("")
        ->setLastModifiedBy("")
        ->setTitle("数据EXCEL导出")
        ->setSubject("数据EXCEL导出")
        ->setDescription("数据EXCEL导出")
        ->setKeywords("excel")
        ->setCategory("result file");
    /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $cellNum = count($table_title);
    for ($i = 0; $i < $cellNum; $i++) {
        $objPHPExcel->setActiveSheetIndex()->setCellValue($cellName[$i].'1', $table_title[$i]);
    }
    for ($i = 2;$i <= count($info) + 1;$i++) {
        for($j = 0;$j < count($table_value);)
            foreach ($table_value as $v) {
                $objPHPExcel->getActiveSheet()->setCellValue("$cellName[$j]$i", $info[$i - 2][$v]);
                $j++;
            }
    }
    header('Content-Type: applicationnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$table_name.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

function safeCache($name, $value = '', $options = null, $tag = null){
    if (is_null($options)){
        $options = config('cache');    //引入配置参数（修正由于框架里面没有对有效时间设置）
    }
    return cache($name, $value, $options, $tag);
}

function generateUniqueOrderno()
{
    do {
        // 生成唯一标识符（这里使用 UUID 和时间戳结合）
        $orderSn = 'S'.date('YmdHis'). str_pad(mt_rand(1, 99999999), 5, '0', STR_PAD_LEFT);
        // 检查数据库中是否存在该单号
        $exists = \app\common\model\BusInquiry::where('sales_no', '=', $orderSn)->find();
    } while ($exists); // 如果存在则继续循环
    return $orderSn;
}

function https_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $headers = array("Content-type: application/json;charset='utf-8'"
            ,   "Accept: application/json",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "Accept:*/*");

    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch); //运行curl

    curl_close($ch);
    return $data;
}

function curl_get($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做证书校验,部署在linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}

function create_token($info,$out_time){
    return substr(md5($info.$out_time),5,26);
}

function getCharInfo($len=32){
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789';
    mt_srand(10000000*(double)microtime());
    for($i = 0,$str = '',$lc = strlen($chars)-1;$i<$len;$i++){
        $str .= $chars[mt_rand(0,$lc)];
    }
    return $str;
}

function tree_info($menu_arr,$parent_id,$diction=0){
    $totall_arr = array();
    foreach ($menu_arr as $temp){
        if($parent_id == $temp['parent_id']){
            $menu_data = array();
            $menu_data["value"] = $temp['name'];
            $menu_data["label"] = $temp['name'];
            if($diction==1){
                $menu_data["dictionary_type"] = $temp['dictionary_type'];
            }
            $menu_data["children"] = tree_info($menu_arr,$temp['id'],$diction);
            $totall_arr[] = $menu_data;
        }
    }
    return $totall_arr;
}